package com.tramy.hpush.server;

import com.tramy.hpush.server.data.ClientAuthInfo;
import com.tramy.hpush.server.data.Message;
import com.tramy.hpush.server.data.PushData;
import com.tramy.hpush.server.data.PushResponse;
import okhttp3.*;

import java.io.IOException;

public class OkHttpUtils {

    private static final OkHttpClient okHttpClient;

    static {
        okHttpClient = new OkHttpClient();
    }

    private OkHttpUtils() {

    }

    public static ClientAuthInfo requestAccessToken(String clientId,
                                                    String clientSecret) throws IOException {
        FormBody params = new FormBody.Builder()
                .add("grant_type","client_credentials")
                .add("client_id", clientId)
                .add("client_secret", clientSecret)
                .build();

        Request request = new Request.Builder()
                .url("https://oauth-login.cloud.huawei.com/oauth2/v3/token")
                .post(params)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        if (response.body() != null) {
            String json = response.body().string();
            return GsonUtils.jsonToPojo(json, ClientAuthInfo.class);
        }else {
            throw new RuntimeException("this okhttp response has used");
        }
    }

    public static PushResponse sendPushData(String appId,
                                            ClientAuthInfo authInfo,
                                            boolean isDebug,
                                            Message message) throws IOException {
        PushData data = new PushData();
        data.setValidateOnly(isDebug);
        data.setMessage(message);
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody params = RequestBody.create(mediaType, GsonUtils.toJson(data));

        Request request = new Request.Builder()
                .url("https://push-api.cloud.huawei.com/v1/" + appId + "/messages:send")
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("Authorization",
                        authInfo.getTokenType() + " " + authInfo.getAccessToken())
                .post(params)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        if (response.body() != null) {
            String json = response.body().string();
            return GsonUtils.jsonToPojo(json, PushResponse.class);
        }else {
            throw new RuntimeException("this okhttp response has used");
        }
    }

}
